% randomly timed steps across the entire field of view
% bcoe@biomed.queensu.ca
% required bcoe functions:
% define_colors
% standard_date(2);
% inputdlg_offscreen;
% questdlg_offscreen;
%
% 2006-nov-28 version 03 added eye tracking 

clc; 
clear;
close all;
% computer specific information
try % prometheus
    home_folder='E:\Data\Queens_fMRI\_bcoe\randomwalk';
    home_folder='C:\Data\Queens_MRI\_bcoe\randomwalk';
    cd(home_folder)
    
    distance2screen=66;% cm
    screenwidth=37.7; %-ish  cm
catch %mri stimulus computer
    home_folder='C:\_User\_bcoe\Data\randomwalk';
    cd(home_folder)
    
    distance2screen=140;% cm ~140cm
    screenwidth=45; % cm 45
    %    pi=pi(); % 6.5 may not have this
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%    Global Defaults    %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

screenRect=get(0,'ScreenSize');
c_x=screenRect(3)/2;
c_y=screenRect(4)/2;
x_adj=screenRect(3)/512;
y_adj=screenRect(4)/512;
if any(screenRect<1)
    error('screen size has been changed after opening matlab')
end
dphs=atan((screenwidth/2)/distance2screen)*180/pi;% degrees per half screen
pixperdeg=screenRect(3)/2/dphs; % pixels per degree
RecordStart=132; % for IScan
RecordStop=136;  % for IScan
c=define_colors(256);
c.BACKGROUND=c.BLACK;
c.FIX=c.RED;
c.TGT=c.GREEN;
round_clock=round(clock);

clear distance2screen screenwidth dphs screenRect

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%   ASSIGN PARAMETERS   %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% First, try to load table of parameter names and set values
try % this should speed things along if your running a few studies on the same subject
    load('temp')
    for par = 1:size(Parameters,1)% assign each parameter in the table to its value
        eval([Parameters{par,1} '=''' Parameters{par,2} ''';']); % for string entries
    end   
    sub_inits% check if it exists
    sub_code% check if it exists
    if ~strcmp(kyou,datestr(now,'yyyy-mmm-dd'))% check if it exists & ...
        error;% if today's date doesn't match the date in the temp file force 'try' to fail
    end   
    file_nb=str2num(file_nb)+1;% check if it exists & increment
    if file_nb<10
        file_nb=['0' num2str(file_nb)]
    else
        file_nb=num2str(file_nb)
    end
    TR% check if it exists
    t1eq_scans% check if it exists
    abab%=num2str(abs(str2num(abab)-2)+1);
    tgt_ecc
    sac_dur
    fix_dur
    clc;
catch % else start from scratch
    disp(' -> loading default settings');
    pause(.5)
    sub_inits='XXX';
    sub_code='00000';
    kyou=datestr(now,'yyyy-mmm-dd');
    file_nb='00';
    TR='5000';
    t1eq_scans='3';  %T1 equilization scans
    abab='1';
    tgt_ecc='-8:.4:8';
    sac_dur='TR*4';
    fix_dur='TR*2';
end

Parameters={...% variable  value           'discription'                           string or number?
        'sub_inits',	sub_inits,		'Subjects 3 Initials (ABC)',            's';...
        'sub_code',	    sub_code,		'Subjects 5 Digit MRI code (00000)',                                's';...        
%        'kyou',		    kyou,		    'Today''s Date (yyyy-mm-dd)',           's';...
        'file_nb',		file_nb,		'File # (or run #, always 2 digits):',  's';...
%        'prescan_time',	prescan_time,	'Prescan Normalization Time (in secs, 0 = wait for MR trigger)', 'n';...
        'TR',	        TR,          	'TR (in millisecs)',                    'n';...
        't1eq_scans',	t1eq_scans, 	'# of T1 saturation scans (in TR)',     'n';...
        'abab',	        abab, 	        'ABABA, BABAB, ABAB, BABA (1, 2, 3, or 4)',              'n';...
        'tgt_ecc',	    tgt_ecc,        ['Number of targets across screen: ' num2str(length(tgt_ecc))] ,   'n';...
        'sac_dur',	    sac_dur,        'Duration of Saccade blocks (in ms or "TR*n" )',   'n';...
        'fix_dur',	    fix_dur,        'Duration of Fixation blocks (in ms or "TR*n" )',  'n';...
    };

save('temp','Parameters','kyou');    % saves temp data (still in string format)
%now set the numeric data to numbers
for par= find(char(Parameters{:,4})=='n')' % for numeric entries
    eval([Parameters{par,1} '=[' Parameters{par,2} '];']); 
    eval([Parameters{par,1} '=' Parameters{par,1} '(:);' ]); % force to vertical
end
clear par

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% define states (video presentation)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
i=1; 
%S.WAIT   =i;    t_state{i}='Waiting';      i=i+1;
S.T1EQ   =i;    t_state{i}='T1 Equ';        i=i+1;
S.L_FIX  =i;    t_state{i}='Left Fixation'; i=i+1;
S.R_FIX  =i;    t_state{i}='Right Fixation';i=i+1;
S.L_WALK =i;    t_state{i}='Left Walk';     i=i+1;
S.R_WALK =i;    t_state{i}='Right Walk';    i=i+1;
S.ENDTASK=i;    t_state{i}='End-Task';      i=i+1;

%state_time(1:i-1)=0;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% define state timing & update parameters
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
file_name=[Parameters{1,2} '.' kyou '_' Parameters{3,2} ];

update=2;
while update
    if update==1 % skip interface the first time to do calculations
        clc;
        fprintf('%s \n',['Duration of Paragigm: ' num2str(max(state_end_time)) 'ms or ' num2str(floor(max(state_end_time)/60000)) ':' num2str(rem((max(state_end_time)/60000)*60,60)) 'min.'])
        fprintf('%s \n',['Total # of Volumes: ' num2str((max(state_end_time))/TR)  ])
        fprintf('%s \n',['TR=' num2str(TR) ', Skip: ',num2str(t1eq_scans) ,', Active: ',num2str(sac_dur/TR) ,', Baseline: ' num2str(fix_dur/TR) ])
        fprintf('%s \n',['(' num2str((max(state_end_time))/TR) '*TR)=' num2str(eval(['(' num2str((max(state_end_time))/TR) '*TR)']))]);
        fprintf('%s \n','#  State:          START: FINISH: TR''s: ')
        for i=1 :length(state_event)
            spacea='';spacea(1:length(char(t_state{:}))+1-length(t_state{state_event(i)}))=' ';
            spaceb='';spaceb(1:7-length(num2str(state_start_time(i))))=' ';
            spacec='';spacec(1:7-length(num2str(state_end_time(i))))=' ';
            spaced='';spaced(1:5-length(num2str(duration_o_state(state_event(i))/TR) ))=' ';
            fprintf('%s \n',[num2str(state_event(i)) ': '  t_state{state_event(i)} spacea spaceb num2str(state_start_time(i)) spacec num2str(state_end_time(i)) spaced num2str(duration_o_state(state_event(i))/TR) ])
        end
        
        cd(home_folder)
        load('temp') % gets the string versions back
        Parameters(7,3)={['Number of targets across screen: ' num2str(length(tgt_ecc))]};
        [ParamInputs update] = inputdlg_offscreen(Parameters(:,3), ['Enter Parameters - ' file_name] , 1, Parameters(:,2));
        if isempty(ParamInputs);
            disp('Task Canceled');
            return
        end
        kyou=datestr(now,'yyyy-mmm-dd');% force to todays date
        [Parameters{:,2}] = deal(ParamInputs{:});
        clear ParamInputs
        save('temp','Parameters','kyou');    % saves temp data (still in string format)
        for par=1:length(Parameters)
            if char(Parameters{par,4})=='n' % for numeric entries
                eval([Parameters{par,1} '=[' Parameters{par,2} '];']);
                eval([Parameters{par,1} '=' Parameters{par,1} '(:);' ]); % force to vertical
            else
                eval([Parameters{par,1} '=''' Parameters{par,2} ''';']);            
            end    
        end
        % save data file
        folder=[Parameters{1,2} '.' kyou];
        if ~exist(folder,'dir')
            eval(['mkdir ' folder]);
        end
        eval(['cd ' folder]);
        file_name=[Parameters{1,2} '.' kyou '_' Parameters{3,2} ];
        if exist([file_name,'.mat'],'file') 
            yesno=questdlg_offscreen(['File Exits! Overwrite ',file_name,'.mat?'],'Be Careful!','Yes','No','No');
            if yesno(1)=='N'
                disp(['File Exists: ' file_name])
                update=1;
                file_nb=str2num(file_nb)+1;% increment
                if file_nb<10
                    file_nb=['0' num2str(file_nb)];
                else
                    file_nb=num2str(file_nb);
                end
                Parameters{3,2}=file_nb;
                cd(home_folder)
                save('temp','Parameters','kyou');    % saves temp data (still in string format)
                eval(['cd ' folder]);
            end
            clear yesno;
        end
    end % if update==1
    if update>1, update=1;end 
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % start do time stuff  
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % S.T1EQ   =i;    t_state{i}='T1 Equ';        i=i+1;
    % S.L_FIX  =i;    t_state{i}='Left Fixation'; i=i+1;
    % S.R_FIX  =i;    t_state{i}='Right Fixation';i=i+1;
    % S.L_WALK =i;    t_state{i}='Left Walk';     i=i+1;
    % S.R_WALK =i;    t_state{i}='Right Walk';    i=i+1;
    % S.ENDTASK=i;    t_state{i}='End Task';      i=i+1;

    number_o_block=6;
    duration_o_state(S.T1EQ)=t1eq_scans*TR;% dummy or T1Eq scans
    duration_o_state(S.L_FIX)=round(fix_dur/TR)*TR;
    duration_o_state(S.L_WALK)=round(sac_dur/TR)*TR;
    duration_o_state(S.R_FIX)=round(fix_dur/TR)*TR;
    duration_o_state(S.R_WALK)=round(sac_dur/TR)*TR;
    duration_o_state(S.ENDTASK)=0;

    state_event=[S.T1EQ];            
    switch abab
        case 1
            for i= 1:(number_o_block)/2
                state_event=[state_event S.L_WALK S.L_FIX S.R_WALK S.R_FIX ];
            end
            state_event=[state_event S.L_WALK S.L_FIX ];
        case 2
            for i= 1:(number_o_block)/2
                state_event=[state_event S.R_WALK S.R_FIX S.L_WALK S.L_FIX ];
            end
            state_event=[state_event S.R_WALK S.R_FIX ];
        case 3
            for i= 1:(number_o_block)/2
                state_event=[state_event S.L_WALK S.L_FIX S.R_WALK S.R_FIX ];
            end
        case 4
            for i= 1:(number_o_block)/2
                state_event=[state_event S.R_WALK S.R_FIX S.L_WALK S.L_FIX ];
            end
    end
    state_event(end+1)=S.ENDTASK; 
    
    state_duration=duration_o_state(state_event);
    state_duration=state_duration(:);
    state_event=state_event(:);
    state_end_time=cumsum(state_duration);
    state_start_time=[0; state_end_time(1:end-1) ];
    %         [state_event state_duration state_end_time] ;

end % while update

save('temp','Parameters','kyou')% reload at end for saving with the A structure
s_TR(1:5-length(num2str(TR)))=' ';
s_TR=[s_TR, num2str(TR)]; %
m_TR=num2str((max(state_end_time))/TR); %for report
walking=0:sac_dur/length(tgt_ecc):sac_dur;walking(1)=[];
clear spacea spaceb spacec spaced number_o_block Parameters kyou file_nb sub_inits par fix_dur i update sac_dur t1eq_scans abab sub_code 
% eval(['cd ' home_folder]);


stim_size=.1;% radius of stim
s_circle=[-1 -1	1 1]*pixperdeg*stim_size;      						% stimulus circle
fix_b=floor([c_x c_y c_x c_y]+([-1 -1	1 1]*pixperdeg*(stim_size/4.5)));	% fixation middle
fix_a=floor([c_x c_y c_x c_y]+([-1 -1	1 1]*pixperdeg*stim_size));	% fixation circle
% Number of Locations
% 135  90  45
% 180  +  360
% 225 270 315
% angle of 0 means ecc of 0 and vice versa!
loc_AngEcc(:,2)=tgt_ecc;
loc_AngEcc(:,1)=360;
n_loc=length(loc_AngEcc);
loc_XY=[]; 
[ loc_XY(:,1) loc_XY(:,2)]=polar2cart(loc_AngEcc(:,1),loc_AngEcc(:,2),1);   
pixloc_XY=[];
pixloc_XY (:,1)=(loc_XY (:,1)*pixperdeg)+c_x;% set ang&ecc to x&y based on screen size
pixloc_XY (:,2)=(loc_XY (:,2)*pixperdeg)+c_y;
for i=1:n_loc
    tgt_rects(i,:)=floor([pixloc_XY(i,:) pixloc_XY(i,:)]+s_circle); % for use with mac's LeToRiBo rect shite
end
clear pixloc_XY loc_XY loc_AngEcc stim_size s_circle 

%%%%%%%%%%%%%%%%%%%%%%%%
% start serial stuff
sizeodata=1;
simpleserial('close');
simpleserial('open','com1',115200);
% how do i send the command window to the front? 
figure('Visible','off')
uimenufcn(gcf,'WindowCommandWindow');
close(gcf)% hackity hack hack hack!!!
if simpleserial('bytesready')==0,clc, fprintf('%s \n','please check ''Track Active'' (''q'' to bypass serial)' ) ;end
keyCode=0;
while simpleserial('bytesready')==0 
    [keyIsDown,secs,keyCode] = KbCheck; % Warning: mxSetLogical is deprecated and will not be supported in the future. Please refer to the Release Notes for information on updating your code
    if keyCode(27)% ESC on pcwin
        simpleserial('close');
        disp('Task Aborted');
        return
    end    
    if keyCode(81)% 'q' on pcwin
        fprintf('%s \n','not using serial input ');
        sizeodata=0;
        break
    end
end
if sizeodata
    clc
    pause(.25);% wait for data to accumulate
    fred=[];
    temp=simpleserial('read',inf,'int16');
    fred=length(temp)-max(find(temp==17476));    
    if isempty(fred), fprintf('%s \n','can''t find magic #:');,end
    i=0;
    while isempty(fred)   
        temp=simpleserial('read',1,'int8');
        pause(.25);beep% wait for data to accumulate
        temp=simpleserial('read',inf,'int16');
        fred=length(temp)-max(find(temp==17476));
        i=i+1;fprintf(' %d', i);        
    end
    [keyIsDown,secs,keyCode] = KbCheck; % Warning: mxSetLogical is deprecated and will not be supported in the future. Please refer to the Release Notes for information on updating your code
    if keyCode(27)% ESC on pcwin
        simpleserial('close');
        disp('Task Aborted');
        return
    end    
    sizeodata=mean(diff(find(temp==17476)));
    pause(.1);
    simpleserial('read',(fred+1)*2,'int16');% to align the buffer to the majic number (17476) 
end 
%%%%%%%%%%%%
% finally start actual task
% how do i send the command window to the front? 
figure('Visible','off')
uimenufcn(gcf,'WindowCommandWindow');
close(gcf)% hackity hack hack hack!!!

[w,screenRect] = SCREEN(0,'OpenWindow',0,[],32);
pause(.01)
SCREEN(w,'fillrect',c.BACKGROUND); 
[buffer,rect]  = SCREEN(0,'OpenOffscreenWindow',0,[],32);
SCREEN(buffer,'fillrect',c.BACKGROUND); 
SCREEN(w,'TextStyle',1);% 0=plain, 1=bold, 2=italics, 3=1&2,  4=underlined, 5=4&1,6=4&2, 7=4&3. rem(?,8)
[oldFontName,oldFontNumber]=SCREEN(w,'TextFont','Tahoma');
SCREEN(w,'TextSize',40);
ttext='Waiting for the MRI to start';
twidth=SCREEN(w,'TextWidth',ttext);
SCREEN(w,'DrawText',ttext,c_x-(twidth/2),c_y-100,c.GREEN);
SCREEN(w,'TextSize',40);
screen(w,'waitblanking');
refresh=getsecs;
screen(w,'waitblanking',10);
refresh=(getsecs-refresh)/10*1000;
% prepare t1_sat screen;
if state_event(2)==S.R_WALK % hack, but if next walk is right, start with left fix
    next_tgt=1;increment=1;
else
    next_tgt=n_loc;increment=-1;
end
SCREEN(buffer,'filloval',c.FIX,tgt_rects(next_tgt,:));  % draw left fix            


buttons=0; % prevent from skipping mouse button loop
while buttons(1)==0  
    warning off MATLAB:DeprecatedLogicalAPI;
    [keyIsDown,secs,keyCode] = KbCheck; % Warning: mxSetLogical is deprecated and will not be supported in the future. Please refer to the Release Notes for information on updating your code
    warning on MATLAB:DeprecatedLogicalAPI;
    keyCode=min(find(keyCode));
    if keyCode==27% ESC on pcwin
        SCREEN('Closeall');
        simpleserial('close');
        disp('Task Aborted');
        return
    end    
    if keyCode==48+5% '5%' on pcwin the new mri trigger
        buttons=1;
    end    
    temp=simpleserial('bytesready'); % make sure to 
    if temp > sizeodata;
        data= simpleserial('read',floor(temp/sizeodata)*sizeodata,'int16');   
    end
end

simpleserial('write', char(RecordStart)); % for IScan
%RecordStop=136;  % for IScan
HideCursor
%screen(w,'waitblanking');
SCREEN('CopyWindow',buffer,w);
tic
abs_start_time=(getsecs);
%ctim=floor((getsecs-abs_start_time)*1000); % current time in milliseconds
index=1;
state=state_event(index);
state_time=0;
simpleserial('write', char(state)); % for IScan
trial=0;
next_TR=1;
report=1;
while state < S.ENDTASK
    switch state_event(index+1)  % draw next state to buffer   
        case S.L_FIX % left fixation
            SCREEN(buffer,'filloval',c.FIX,tgt_rects(1,:));             
        case S.R_FIX % right fixation
            SCREEN(buffer,'filloval',c.FIX,tgt_rects(n_loc,:));         
        case S.L_WALK % walk to the left
            fred = refresh*((ceil(rand(1,floor(n_loc/2))*5)-3)*6);
            walk_time=walking(end:-1:1);
            walk_time(1:2:end-1)=walk_time(1:2:end-1)+fred;            
            SCREEN(buffer,'filloval',c.TGT,tgt_rects(n_loc,:));  
            next_tgt=n_loc;this_tgt=n_loc;
            increment=-1;
        case S.R_WALK % walk to the right
            fred = refresh*((ceil(rand(1,floor(n_loc/2))*5)-3)*6);
            walk_time=walking;
            walk_time(1:2:end-1)=walk_time(1:2:end-1)+fred;            
            SCREEN(buffer,'filloval',c.TGT,tgt_rects(1,:));  
            next_tgt=1;this_tgt=1;
            increment=1;
    end %switch status         
    ctim     =floor((getsecs-abs_start_time)*1000); % current time in milliseconds

    while ctim < state_end_time(index) & state < S.ENDTASK 
        if ctim>=report+1000 | ceil(ctim/TR)>next_TR
            clc;
            fprintf('%s \n',['   State: ' t_state{state}  ,' (',num2str(next_tgt),':', num2str(n_loc) ,')']);
            fprintf('%s \n',[s_TR,'-TR: ' num2str(ceil((ctim)/TR)),' of ',m_TR ]);
            fprintf('%s \n',['    Time: ' num2str(ctim)]);
            fprintf('%s \n',['NextTime: ' num2str(floor((state_end_time(index))))]);
            fprintf('%s \n',['Remaning: ' num2str((state_end_time(index)-ctim))]);
            ctim=floor((getsecs-abs_start_time)*1000); % current time in milliseconds
            report=floor(ctim/1000)*1000;
            next_TR=ceil(ctim/TR);
        end         
        if (state==S.L_WALK | state==S.R_WALK) & ctim>=walk_time(next_tgt)
%            walk_time=round(ctim+(duration_o_state(state)/(n_loc+1))+(refresh*((ceil(rand*5)-3)*6)));
            screen(w,'waitblanking');
            SCREEN(w,'filloval',c.BACKGROUND,tgt_rects(next_tgt,:));  % erase old target
            if (next_tgt > 1 & increment < 0) | ( next_tgt < n_loc & increment > 0),
                next_tgt=next_tgt+increment;
            end
            SCREEN(w,'filloval',c.TGT,tgt_rects(next_tgt,:));  % draw  new target
            simpleserial('write', char(state)); % for IScan
            ctim=floor((getsecs-abs_start_time)*1000); % current time in milliseconds
        end
        %warning off MATLAB:DeprecatedLogicalAPI
        [keyIsDown,secs,keyCode] = KbCheck; % Warning: mxSetLogical is deprecated and will not be supported in the future. Please refer to the Release Notes for information on updating your code
        %warning on MATLAB:DeprecatedLogicalAPI
        if keyCode(27)% ESC on pcwin
            state = S.ENDTASK; % S.ENDTASK to exit
        end
        ctim=floor((getsecs-abs_start_time)*1000); % current time in milliseconds
    end % while buttons(1)==0  & getsecs < next_time(index) %state_time(index) 
    if state < S.ENDTASK, 
        index=index+1;
        state=state_event(index); 
        if state_duration(index)>0
            screen(w,'waitblanking');
            SCREEN('CopyWindow',buffer,w);
            SCREEN(buffer,'fillrect',c.BACKGROUND);
        end  
        if (state==S.L_WALK | state==S.R_WALK)
            walk_time=walk_time+ctim;
        end
    end
    simpleserial('write', char(state)); % for IScan
    ctim=floor((getsecs-abs_start_time)*1000); % current time in milliseconds
    state_time(end+1)=ctim;
end % while state  

simpleserial('write', char(RecordStop)); % for IScan
simpleserial('close');

load('temp')
A=[];
A.file_name=file_name;
A.clock=round_clock;
A.parameters=Parameters;
A.t_state=t_state;
A.pixperdeg=pixperdeg;
A.screenRect=screenRect;
A.colors=c;
A.state_start_time=state_start_time;
A.state_end_time=state_end_time;
A.state_time=state_time';
A.state_event=state_event;
save([A.file_name '.mat'],'A');
delete('temp.mat');
%[ A.state_event state_start_time A.state_time]
%[state_time' state_start_time]
temp=(c.M_GREY-c.BACKGROUND)./60;
for i = 1:60 % fade to ?_GREY algorythm
    SCREEN(w,'fillrect',round(c.BACKGROUND+(temp*i)));
    screen(w,'waitblanking');
end  

SCREEN(w,'TextStyle',1);% 0=plain, 1=bold, 2=italics, 3=1&2,  4=underlined, 5=4&1,6=4&2, 7=4&3. rem(?,8)
[oldFontName,oldFontNumber]=SCREEN(w,'TextFont','Tahoma');
SCREEN(w,'TextSize',58);
ttext='thank you!';
twidth=SCREEN(w,'TextWidth',ttext);
SCREEN(w,'DrawText',ttext,c_x-(twidth/2),c_y-60,c.BLUE);
ttext='please rest.';
twidth=SCREEN(w,'TextWidth',ttext);
SCREEN(w,'DrawText',ttext,c_x-(twidth/2),c_y+60,c.BLUE);
SCREEN(w,'TextSize',40);


pause(2)

ShowCursor
SCREEN('closeall');
dir

return






























screen(w,'waitblanking');
    SCREEN('CopyWindow',buffer,w);
    simpleserial('write', char(state)); % for IScan

    s_time(index)=floor(getsecs*1000);
    tgt_switch=s_time(index);
%     next_tgt=0;
%     this_tgt=1;
    buttons=0; % prevent from skipping mouse button loop
    tgt_switch=floor(getsecs*1000)+800+(refresh*((ceil(rand*5)-3)*6));
    tgt_duration=floor(getsecs*1000)+floor(getsecs*1000); %force to be impossible first time around

simpleserial('write', char(RecordStop)); % for IScan
simpleserial('close');

if buttons<1, pause(2); end % just to add a bit of buffer unless esc is pressed
A.s_time=s_time-abs_start_time;
A.e_time=e_time-abs_start_time;
A.state=state;
save([A.file_name '.mat'],'A');
disp(['Saved file: ' A.file_name '.mat']);
SCREEN(w,'fillrect',c.BACKGROUND);
temp=(c.M_GREY-c.BACKGROUND)./60;
for i = 1:60 % fade to ?_GREY algorythm
    SCREEN(w,'fillrect',round(c.BACKGROUND+(temp*i)));
    screen(w,'waitblanking');
end    

SCREEN(w,'TextStyle',1);% 0=plain, 1=bold, 2=italics, 3=1&2,  4=underlined, 5=4&1,6=4&2, 7=4&3. rem(?,8)
[oldFontName,oldFontNumber]=SCREEN(w,'TextFont','Tahoma');
SCREEN(w,'TextSize',58);
ttext='thank you!';
twidth=SCREEN(w,'TextWidth',ttext);
SCREEN(w,'DrawText',ttext,c_x-(twidth/2),c_y-60,c.BLUE);
ttext='please rest.';
twidth=SCREEN(w,'TextWidth',ttext);
SCREEN(w,'DrawText',ttext,c_x-(twidth/2),c_y+60,c.BLUE);
SCREEN(w,'TextSize',40);
buttons=0;
while buttons(1)==0 
    %[x y buttons]=getmouse;
    warning off MATLAB:DeprecatedLogicalAPI;
    [keyIsDown,secs,keyCode] = KbCheck; % Warning: mxSetLogical is deprecated and will not be supported in the future. Please refer to the Release Notes for information on updating your code
    warning on MATLAB:DeprecatedLogicalAPI;
    if sum(keyCode)% ESC on pcwin
        buttons=1; % get out of this loop 
        status=0;% get out of status loop
    end
end
showcursor;
SCREEN(w,'Close');
SCREEN(buffer,'Close');
cd
dir